package com.ywl.study.transaction.manager.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class NettyServer {
    @PostConstruct
    public void start(){
        start("localhost",8080);
        System.out.println("Netty Server 启动成功");
    }

    public void start(String hostname,int port){
        //服务类
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            //设置线程池
            bootstrap.group(boss,worker);
            //设置socket工厂
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new NettyServerHandler());
                };
            });
            //tcp设置参数
            bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//连接缓冲区的大小
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);//维持链接的活跃，清除死连接
            bootstrap.option(ChannelOption.TCP_NODELAY, true);//关闭延迟发送

            //绑定端口
            ChannelFuture future =  bootstrap.bind(8080);

            System.out.println("start");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close(){
//        //等待服务端关闭
//        future.channel().closeFuture().sync();
//        boss.shutdownGracefully();
//        worker.shutdownGracefully();
    }
}
